<?php

/**
 * Capital Direct Lending (http://www.philbsd.com/cdl)
 *
 * Copyright (C) 2008 Philippine Business Solution Developers <http://www.philbsd.com>
 * All rights reserved.
 *
 *
 * LICENSE
 *
 * This source file is subject to the GNU General Public License v3 license
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@philbsd.com so we can send you a copy immediately.
 *
 * @copyright  (c) 2008 Philippine Business Solution Developers. (http://www.philbsd.com)
 * @license    http://www.gnu.org/licenses/gpl-3.0.txt
 * @version    $Id: loan.php 254 2008-05-11 10:08:15Z artiskool $
 */

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Loan extends SB_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->_data['menuLoan'] = true;
		$this->load->model('Loans');
	}

	public function index()
	{
		$this->_data['msg'] = $this->session->flashdata('msg');
		$this->_data['records'] = $this->Loans->getLoanIndex();
		$this->render('loan/index.shtml');

		if (isset($_POST['del_x'])) {

    	/* delete selected loan */
    		if (is_array($_POST['loan_id']) && count($_POST['loan_id'])) {
        		foreach ($_POST['loan_id'] as $loani) {
                	$this->_data['loan_id'] = $loani;
					if ($this->input->post('loan_id')) {
						$this->db->delete('loans', array('id' => $this->input->post('loan_id')));
					}
        		}
        	    $this->_data['success_msg'] = "Successfully deleted.";
        		$this->render('loan/index.shtml');
        		exit;
    		}
		}
	}

	public function add($page = 'page1')
	{
		$this->load->library('validation');

		if ($page == 'page1') {
			if (isset($_POST['next'])) {
				$rules['Loan/borrower_id'] = "required";
				$rules['Loan/coborrower_id'] = "required";
				$rules['Loan/inquiry_date'] = "required";
				$rules['Loan/status'] = "required";
				$rules['Loan/collector_id'] = "required";
				$rules['Loan/loan_type'] = "required";
				$rules['Loan/principal_amount'] = "required";
				$rules['Loan/interest_amount'] = "required";
				$rules['Loan/loan_amount'] = "required";
				$rules['Loan/surcharges'] = "required";
				$rules['Loan/number_payments'] = "required";
				$rules['Loan/payment_terms'] = "required";
				$rules['Loan/daily_payment'] = "required";
				$this->validation->set_rules($rules);

				$fields['Loan/borrower_id'] = 'Borrower ID';
				$fields['Loan/coborrower_id'] = "Co-borrower ID";
				$fields['Loan/inquiry_date'] = "Inquiry Date";  
				$fields['Loan/status'] = "Loan Status";
				$fields['Loan/collector_id'] = "Collector ID";
				$fields['Loan/loan_type'] = "Loan Type";
				$fields['Loan/principal_amount'] = "Principal";
				$fields['Loan/interest_amount'] = "Interest Amount";
				$fields['Loan/loan_amount'] = "Total Loan Amount";
				$fields['Loan/surcharges'] = "Surcharges";
				$fields['Loan/number_payments'] = "Loan Payment (Days)";
				$fields['Loan/payment_terms'] = "Payment Terms";
				$fields['Loan/daily_payment'] = "Daily Payment";
				$fields['Loan/start_date'] = "Loan Start Date";
				$this->validation->set_fields($fields);

				if ($this->validation->run()) {
					$valid_borrowers = true;
					$sql = "SELECT id FROM borrowers  WHERE id = '{$this->_swordPost['Loan']['borrower_id']}'";
					$result = $this->db->query($sql);
					if ($result->num_rows() <= 0) {
						$msg = "Borrower ID # {$this->_swordPost['Loan']['borrower_id']} does not exists.";

						if (isset($this->_data['msg'])) {
							$this->_data['msg'] .= "\n<br />$msg";
						} else {
							$this->_data['msg'] = $msg;
						}
						$valid_borrowers = false;
					}

					$sql = "SELECT id FROM borrowers  WHERE id = '{$this->_swordPost['Loan']['coborrower_id']}'";
					$result = $this->db->query($sql);
					if ($result->num_rows() <= 0) {
						$msg = "Coborrower ID # {$this->_swordPost['Loan']['borrower_id']} does not exists.";
						if (isset($this->_data['msg'])) {
							$this->_data['msg'] .= "\n<br />$msg";
						} else {
							$this->_data['msg'] = $msg;
						}
						$valid_borrowers = false;
					}

					if ($valid_borrowers) {
						$data = $this->_swordPost['Loan'];
						$this->session->set_userdata('Loan', $data);
						header("Location: {$this->_data['baseUrl']}loan/add/addpage2.html");
						exit;
					}
				}
			}
			$sql = "SELECT * FROM loan_matrix";
			$result = $this->db->query($sql);
			$this->_data['loan_matrix'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['loan_matrix'][] = $row;
				}
			}
			$this->render('loan/add.shtml');
		} else if ($page == 'addpage2') {
			$loan_info = $this->session->userdata('Loan');
			//print_r($loan_info);
			
			$this->_data['borrower_id'] = $loan_info['borrower_id'];
			$sql = "SELECT * FROM businesses WHERE borrower_id = '{$loan_info['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['businesses'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['businesses'][] = $row;
				}
			}
			$sql = "SELECT * FROM collaterals WHERE borrower_id = '{$loan_info['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['collaterals'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['collaterals'][] = $row;
				}
			}
			$sql = "SELECT * FROM notes WHERE borrower_id = '{$loan_info['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['notes'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['notes'][] = $row;
				}
			}
			if (isset($_POST['next'])) {
				header("Location: {$this->_data['baseUrl']}loan/add/addpage3.html");
				exit;
			}
			$this->render('loan/addpage2.shtml');
		} else if ($page == 'addpage3') {
			$this->_data['loan'] = $this->session->userdata('Loan');
			$sql = "SELECT * FROM profiles p RIGHT JOIN borrowers b ON p.id=b.profile_id  WHERE b.id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['borrower'] = array();
			if ($result->num_rows() > 0) {
				$this->_data['borrower'] = $result->row_array();
			}
			$sql = "SELECT * FROM profiles p RIGHT JOIN borrowers b ON p.id=b.profile_id  WHERE b.id = '{$this->_data['loan']['coborrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['coborrower'] = array();
			if ($result->num_rows() > 0) {
				$this->_data['coborrower'] = $result->row_array();
			}
			$sql = "SELECT * FROM businesses WHERE borrower_id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['businesses'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['businesses'][] = $row;
				}
			}
			$sql = "SELECT * FROM collaterals WHERE borrower_id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['collaterals'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['collaterals'][] = $row;
				}
			}
			$sql = "SELECT * FROM notes WHERE borrower_id = '{$this->_data['loan']['borrower_id']}'";
			$result = $this->db->query($sql);
			$this->_data['notes'] = array();
			if ($result->num_rows() > 0) {
				foreach ($result->result_array() as $row) {
					$this->_data['notes'][] = $row;
				}
			}
			if (isset($_POST['save_record'])) {
				$this->db->trans_begin();
				$data = $this->session->userdata('Loan'); 
				$this->db->insert('loans', $data);

				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$errMsg = "Failed to add!";
					if (isset($this->_data['msg'])) {
						$this->_data['msg'] .= $errMsg;
					} else {
						$this->_data['msg'] = $errMsg;
					}
				} else {
					$this->db->trans_commit();
					$this->session->set_flashdata('msg', "Successfully saved!");
					header("Location: {$this->_data['baseUrl']}loan.html");
					exit;
				}
			}
			$this->render('loan/addpage3.shtml');
		}
	}

	public function view($id)
	{
		$this->_data['record'] = $this->Loans->getLoan($id);
		$this->render('loan/view.shtml');
	}
    public function edit_loan($id)
	{
        $this->_data['record'] = $this->Loans->editLoan($id);
		$this->render('loan/edit_loan.shtml');
        
        // editting loan
        if (isset($_POST['Loan/application_date'])) {
            $this->db->trans_begin();
		    $data = $this->_swordPost['Loan'];
			$this->db->where('id', $id);
            $this->db->update('loans', $data);
            $this->db->trans_commit();
            $this->session->set_flashdata('msg', "Successfully saved!");
            header("Location: {$this->_data['baseUrl']}/loan/view/{$id}.html");
			exit;
        }
	}

    function popdel($loan_id)
	{
		$this->_data['loan_id'] = $loan_id;
		if ($this->input->post('loan_id')) {
			$this->db->delete('loans', array('id' => $this->input->post('loan_id')));
			$this->_data['success_msg'] = "Successfully deleted.";
		}
		$this->render('loan/popdel.shtml', array(), 'popup.shtml');
	}

 	function popgenerate($id)
	{
        $this->_data['loan_id'] = $id;
        if ($this->input->post('loan_id')) {
        	$data = $this->Loans->getLoan($this->input->post('loan_id'));
		  	if (!empty($data['start_date']) && !empty($data['pn_signed_date']) && $data['status'] == 5) {

				$this->db->trans_begin();
				$this->db->delete('payments', array('loan_id' => $this->input->post('loan_id')));
                $this->db->trans_commit();

        		$day = explode("-",$data['start_date']);
				// terms like daily, weekly, bi-monthly and monthly payments
				if ($data['payment_terms'] == 1) $b = 0;
				else if ($data['payment_terms'] == 2) $b = 6;
                else if ($data['payment_terms'] == 3) $b = 14;
				else if ($data['payment_terms'] == 4) $b = 29;

                $this->db->trans_begin();

        		for($a = 0 ; $a < $data['number_payments'] ; $a++) {
					$ddates = date("D Y-m-d", mktime(0, 0, 0, date("$day[1]"),date("$day[2]")+$a,date("$day[0]"))); 
		    		$dday = explode(" ", $ddates);
                    $dates = date("Y-m-d", mktime(0, 0, 0, date("$day[1]"),date("$day[2]")+$a,date("$day[0]")));

					if ($dday[0] == "Sun") {
						continue;
					}
					if ($dday[0] == "Mon") {
						$daily_payment = (int)$data['daily_payment'] * 2;
	 				} else {
						$daily_payment = $data['daily_payment'];
					}
					$payment['loan_id'] = $id;
					$payment['amount_due'] = $daily_payment;
                	$payment['due_date'] = $dates;

					$this->db->insert('payments', $payment);
					$a = $a + $b;
				}
                $this->db->trans_commit();
	            $this->_data['success_msg'] = "Successfully created.";
		  	} else {
              	$this->_data['success_msg'] = "Unable to create payments.";
			}
		}
		$this->render('loan/popgenerate.shtml', array(), 'popup.shtml');
	}

}
